package com.lanproperiesinternal.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lanproperiesinternal.baidu.TransApi;
import com.lanproperiesinternal.config.OrderedProperties;
import com.lanproperiesinternal.enums.LanguageEnum;
import com.lanproperiesinternal.util.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Properties;

/**
 * @author kezhihui
 * @date 2022/05/16
 *
 */
@Controller
@Slf4j
public class ChangeLanguageController {
    @Value("${baidu.app.id}")
    private String appId;

    @Value("${baidu.security.key}")
    private String securityKey;

    @Value("${file.tmp.path}")
    private String fileTmpPath;

    @RequestMapping("/")
    public String index(Model model) {
        LanguageEnum[] languageEnums = LanguageEnum.values();
        model.addAttribute("name","hello world");
        model.addAttribute("languageType",languageEnums);
        return "index";
    }

    /**
     *
     * @param multipartFile 源语言文件
     * @param request
     * @param response
     * @return 转换文件结果提示
     */
    @PostMapping("/file/source")
    @ResponseBody
    public String change(MultipartFile multipartFile, HttpServletRequest request,HttpServletResponse response,Model model) {
        String from = request.getParameter("from");
        String to = request.getParameter("to");
        // 读取源语言配置文件信息
        OrderedProperties properties = FileUtil.readOrderedPropertiesFile(multipartFile);

        // 翻译
        TransApi api = new TransApi(appId, securityKey);
        List<String> list = FileUtil.getProValues(properties);
        String sourceStr = String.join("\n", list);

        String transResult = api.getTransResult(sourceStr, from, to);
//        System.out.println("transResult:"+transResult);
        JSONObject jsonObj = (JSONObject) JSON.parse(transResult);
        JSONArray jsonArray = jsonObj.getJSONArray("trans_result");
        String[] dstStr = new String[jsonArray.size()];
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jbj_trans_result = (JSONObject) jsonArray.get(i);
            String dst = jbj_trans_result.get("dst").toString();
            dstStr[i] = dst;
        }

        // 写转换后的语言配置文件
        int index = 0;
        for (String key : properties.stringPropertyNames()) {
            properties.setProperty(key, dstStr[index++]);
        }
        String filePath = fileTmpPath + File.separator + System.currentTimeMillis() + "_" + to + ".properties";
        FileUtil.writeOrderedPropertiesFile(properties,filePath);

        String res = download(response, filePath);
        return res;
    }

    private String download(HttpServletResponse response,String filepath){
        try {
            // 文件地址，真实环境是存放在数据库中的
            File file=new File(filepath);
            // 创建输入流，传入文件对象
            FileInputStream fis=new FileInputStream(file);
            // 设置相关格式
            response.setContentType("application/force-download");
            // 设置下载后的文件名以及header
            response.addHeader("Content-disposition", "attachment;filename="+file.getName());
            OutputStream os = response.getOutputStream();
            // 常规操作
            byte[] buf = new byte[1024];
            int len = 0;
            while((len = fis.read(buf)) != -1) {
                os.write(buf, 0, len);
            }
            os.close();
            fis.close();
            return "转换成功！";
        }catch (IOException e){
            e.printStackTrace();
            return "失败，请重试！";

        }
    }
}
